import * as THREE from "../../../modules/three/three.module.js";
import {toFixedVector} from "../lib/util/StaticMethods.js";
import SphericalUpZ from "../lib/util/SphericalUpZ.js";
import {r2d} from "../lib/CommonConsts.js";

let ptCount = 0;
function setPtCount(num) {
  if (ptCount <= num) {
    ptCount = num + 1;
  }
}
const _spherical = new SphericalUpZ()
const _v = new THREE.Vector3()

class SubAreaVO {
  id = -1
  color = ''
  /**
   * 轮廓顶点序列
   * @type {NormalPointVO[]}
   */
  contour = []
  /**
   * 轮廓中心点的世界坐标
   * @type {THREE.Vector3}
   */
  center = new THREE.Vector3()
  /**
   * 辅助几何平面离中心点的距离
   * @type {number}
   */
  centerAbove = 2
  /**
   * 轮廓顶点的平均朝向
   * @type {THREE.Vector3}
   */
  normal = new THREE.Vector3()
}

// 位置和法向的采样点（局部切平面），用于区域规划，解决曲面喷涂的分区问题
// 规划时，把位置相邻并且 朝向都在一个阈值范围内 采样点规划到一个子区域
// 用于经纬网 IsoLineEntity, IsoLinePlugin
export default class NormalPointVO {
  id = 0
  position = new THREE.Vector3()
  normal = new THREE.Vector3(0, 1, 0)

  constructor() {
    this.id = ptCount++
  }

  getAbovePos() {
    return _v.copy(this.position).add(this.normal)
  }

  getDegrees() {
    _spherical.setFromVector3(this.normal)
    const degPhi = _spherical.phi * r2d
    let degTheta = _spherical.theta * r2d
    return [degPhi, degTheta]
  }

  toJsonObj() {
    const obj = {id: this.id, dir: this.normal.toArray()}
    obj.pos = toFixedVector(this.position, 3).toArray()
    return obj
  }

  fromJsonObj(jsonObj) {
    const id = parseInt(jsonObj.id) || this.id
    setPtCount(id)
    this.id = id
    this.position.fromArray(jsonObj.pos);
    this.normal.fromArray(jsonObj.dir);
    return this;
  }
}
